package com.common.base;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewbinding.ViewBinding;

import com.common.conn.OnTabReselectedListener;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public abstract class BaseFragment<T extends ViewBinding> extends Fragment implements OnTabReselectedListener {
    protected T binding;
    private boolean isViewCreated;
    private boolean isVisibleToUser;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        try {
            Method inflateMethod = getBindingClass().getMethod("inflate", LayoutInflater.class, ViewGroup.class, boolean.class);
            binding = (T) inflateMethod.invoke(null, inflater, container, false);
            isViewCreated = true;
            initView(savedInstanceState);
            lazyLoad();
            return binding.getRoot();
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
            return super.onCreateView(inflater, container, savedInstanceState);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
        isViewCreated = false;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        lazyLoad();
    }

    private void lazyLoad() {
        if (isViewCreated && isVisibleToUser) {
            loadData();
        }
    }

    protected abstract Class<T> getBindingClass();
    protected abstract void initView(Bundle savedInstanceState);
    protected abstract void loadData();
    // 默认实现，子类可重写
    @Override
    public void onTabReselected() {
        // 默认不做任何处理，子类可根据需要重写
    }
}
